<template>
  <div>
    <!--面包屑-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!--数据列表主工作区-->
    <el-card>
      <!--搜索框和添加按钮-->
      <el-row :gutter="20" :class="['search-bar']" >
        <el-col :span="8">
          <el-input placeholder="请输入搜索内容" class="input-with-select" v-model="pageReqParams.query">
            <el-button slot="append" icon="el-icon-search" @click="handleSearchButtonClick()"></el-button>
          </el-input>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="handleAddButtonClick()">添加</el-button>
        </el-col>
        <el-col :span="4">
          <el-button type="danger" @click="handleBatchDeleteButtonClick()">批量删除</el-button>
        </el-col>
      </el-row>

      <!--用户列表-->
      <el-table
        :data="pageInfo.list"
        border
        stripe
        @selection-change="handleSelectionChangeInTable"
        style="width: 100%">
        <el-table-column type="selection"></el-table-column>
        <el-table-column
          prop="id"
          label="ID"
        >
        </el-table-column>
        <el-table-column
          prop="username"
          label="用户名"
        >
        </el-table-column>
        <el-table-column
          prop="realname"
          label="真实姓名"
        >
        </el-table-column>
        <el-table-column
          align="center"
          prop="status"
          label="禁用/启用"
          width="70">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.status" @change="handleUserStatusChange(scope.row)" :active-value="1" :inactive-value="0"></el-switch>
          </template>
        </el-table-column>
        <el-table-column
          prop="roleName"
          label="角色"
        >
        </el-table-column>
        <el-table-column
          prop="modifiedTime"
          label="最后修改时间"
        >
        </el-table-column>


        <el-table-column label="操作" width="250px">
          <template slot-scope="scope">
            <el-tooltip effect="dark" content="修改" placement="top" :enterable="false">
              <el-button type="primary" icon="el-icon-edit"
                         @click="handleModifyButtonClick(scope.row)"></el-button>
            </el-tooltip>

            <el-tooltip effect="dark" content="删除" placement="top" :enterable="false">
              <el-button type="danger" icon="el-icon-delete"
                         @click="handleDeleteButtonClick(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!--数据列表分页-->
      <el-pagination
        @size-change="handlePageSizeChange"
        @current-change="handleCurrentPageNumberChange"
        :current-page="pageInfo.pageNum"
        :page-sizes="pageSizes"
        :page-size="pageInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageInfo.total">
      </el-pagination>
    </el-card>
    <!--添加对话框-->
    <el-dialog title="添加"
               :center="true"
               :visible.sync="addDialogVisible" width="50%">

        <el-form>
          <el-form-item label="用户名">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="角色">
            <el-autocomplete
              class="inline-input"
              v-model="inputRoleName1"
              value-key="name"
              :fetch-suggestions="querySearchRoles"
              placeholder="请输入角色名称"
              @select="handleRoleSelect1"
            ></el-autocomplete>
          </el-form-item>

          <el-form-item label="手机号">
            <el-input v-model="addForm.phone"></el-input>
          </el-form-item>
          <el-form-item label="真实姓名">
            <el-input v-model="addForm.realname"></el-input>
          </el-form-item>
          <el-form-item label="电子邮箱">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="启用/禁用">
            <el-switch v-model="addForm.status" :active-value="1" :inactive-value="0"></el-switch>
          </el-form-item>

        </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancelAddButtonClick()">取 消</el-button>
        <el-button type="primary" @click="handleConfirmAddButtonClick()">确 定</el-button>
      </div>

    </el-dialog>
    <!--修改对话框-->
    <el-dialog title="修改"
               :center="true"
               :visible.sync="modifyDialogVisible" width="50%">

      <el-form>
        <el-form-item label="ID">
          <el-input v-model="currentModifyingData.id" disabled></el-input>
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="currentModifyingData.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="currentModifyingData.password"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-autocomplete
            class="inline-input"
            v-model="inputRoleName2"
            value-key="name"
            :fetch-suggestions="querySearchRoles"
            placeholder="请输入角色名称"
            @select="handleRoleSelect2"
            clearable
          ></el-autocomplete>
        </el-form-item>

        <el-form-item label="手机号">
          <el-input v-model="currentModifyingData.phone"></el-input>
        </el-form-item>
        <el-form-item label="真实姓名">
          <el-input v-model="currentModifyingData.realname"></el-input>
        </el-form-item>
        <el-form-item label="电子邮箱">
          <el-input v-model="currentModifyingData.email"></el-input>
        </el-form-item>
        <el-form-item label="启用/禁用">
          <el-switch v-model="currentModifyingData.status" :active-value="1" :inactive-value="0"></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancelModifyButtonClick()">取 消</el-button>
        <el-button type="primary" @click="handleConfirmModifyButtonClick()">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import {mapMutations,mapState} from 'vuex'
  export default {
    name: "Users",
    data() {
      return {

        // 分页请求时要携带的参数
        pageReqParams: {
          query: '',
          pageNum: 1,
          pageSize: 5
        },
        // 分页信息
        pageInfo: {
          pageNum: 0,
          pageSize: 0,
          total: 0,
          totalPage: 0,
          list: []
        },
        // 分页的大小常量列表
        pageSizes: [5, 10, 20, 30, 50, 100],
        // 添加对话框显示开关
        addDialogVisible: false,
        // 修改对话框显示开关
        modifyDialogVisible: false,
        // 添加对话框中的表单数据
        addForm: {
          email: '',
          gender: 0,
          idNumber: '',
          password: '',
          phone: '',
          realname: '',
          roleId: 0,
          status: 0,
          username: ''
        },

        inputRoleName1:'',

        // 表单的宽度变量
        formLabelWidth: 500,

        currentModifyingData: {},
        inputRoleName2:'',

        idsSelection:[]

      }
    },

    computed:{
      ...mapState({
        roles:state=>state.rbac.roles
      })
    },

    created() {
      this.getPageFunction();
    },
    methods: {

      ...mapMutations(['setRoles']),


      //打开修改对话框
      handleModifyButtonClick(row) {
        this.currentModifyingData = JSON.parse(JSON.stringify(row));

        this.roles.forEach(value=>{
          if(value.id==this.currentModifyingData.roleId){
            this.inputRoleName2 = value.name;
          }
        });

        // TODO 先去请求原始数据，然后显示对话框
        this.modifyDialogVisible = true;
      },

      // 确认修改
      async handleConfirmModifyButtonClick() {

        this.modifyDialogVisible = false;
        //TODO 发起修改请求
        this.api.__api__UsersUpdate(this.currentModifyingData)
          .then(data=>{
            this.getPageFunction();
            this.$message.success(data.message);
          }).catch(error=>{
            this.$message.error(error);
        })
      },

      // 删除
      async handleDeleteButtonClick(row) {

        const res = await this.$confirm('确定要删除?', "提示");
        if (res == 'confirm') {
          // TODO 发起删除请求
          this.api.__api__UsersDelete([row.id])
            .then(data=>{
              this.getPageFunction();
              this.$message.success(data.message);
            }).error(error=>null);
        } else {
          this.$message.info("已取消删除");
        }
      },


      // 批量删除
      async handleBatchDeleteButtonClick(){
        if(this.idsSelection.length==0){
          this.$message.error("请先在表格中选中数据行");
          return;
        }
        const res = await this.$confirm('确定要删除?', "提示");
        if (res == 'confirm') {
          this.api.__api__UsersDelete(this.idsSelection)
            .then(data=>{
              this.getPageFunction();
              this.$message.success(data.message);
            }).catch(error=>null);
        }


      },

      //确认添加
      handleConfirmAddButtonClick() {
        //TODO 发起添加请求
        this.api.__api__UsersAdd(this.addForm)
          .then(data=>{
            this.addDialogVisible = false;
            this.getPageFunction();
            this.$message.success(data.message);
          }).catch(error=>{
            console.error(error);
            return null;
        });
      },

      //点击搜索
      handleSearchButtonClick() {
        this.getPageFunction();
      },

      //页大小改变
      handlePageSizeChange(size) {
        this.pageInfo.pageSize = size;
        this.pageReqParams.pageSize = size;
        this.getPageFunction();
      },

      //页码改变
      handleCurrentPageNumberChange(pageNum) {
        this.pageReqParams.pageNum = pageNum;
        this.getPageFunction();
      },

      //获取一页数据
      getPageFunction() {
        //TODO 发起分页请求
        this.api.__api__UsersPage(this.pageReqParams)
          .then(data => {
            this.pageInfo = data.data;
          }).catch(error => {
          console.log(error);
        })
      },

      //弹出添加对话框
      handleAddButtonClick() {
        this.addDialogVisible = true;
      },

      //取消添加
      handleCancelAddButtonClick() {
        this.addDialogVisible = false;
      },

      //取消修改
      handleCancelModifyButtonClick() {
        this.modifyDialogVisible = false;
      },

      //搜索角色
      querySearchRoles(queryString, callback) {
        if (queryString && queryString.length > 0) {
          callback(this.roles.filter(value => value.name.indexOf(queryString) > -1));
        }else{
          callback(this.roles);
        }
      },
      //新增对话框中的选择角色回调
      handleRoleSelect1(role) {
        this.addForm.roleId = role.id;
      },

      //修改对话框中的选择角色回调
      handleRoleSelect2(role) {
        this.currentModifyingData.roleId = role.id;
      },

      //表格中某行用户状态改变时回调
      handleUserStatusChange(row){
        this.api.__api__UsersStatus({ids:[row.id],status:row.status})
          .then(data=>{
            this.api.__api__UsersOneById(row.id).then(data1=>{
              row.status = data1.data.status;
            }).catch(error=>null);
            this.$message.success(data.message);
          }).catch(error=>{
            row.status = row.status==1? 0:1;
        })
      },

      handleSelectionChangeInTable(selection){
        this.idsSelection.length = 0 ;
        selection.forEach((item)=>this.idsSelection.push(item.id));
      }


    }

  }
</script>

<style scoped>

  .el-pagination {
    margin: 5px;
  }


</style>
